package cn.doyens.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 *    Advice 通知
 */
@Slf4j// 自定义全局异常处理类
@ControllerAdvice(annotations={RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {


    //当@RestController或者@Controller类中的方法抛出该类型异常时 有该方法进行处理
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> saveExceptionHandler(SQLIntegrityConstraintViolationException exception){
           //1.当异常发生事 会传入该异常对象实例  exception 获取异常信息
        String message = exception.getMessage();
        log.info("异常信息内容为:"+message);
        //2.处理异常信息 获取关键字段
        String[] arr = message.split(" ");
        String name = arr[2];
        return R.error(name+"已经存在了");
    }

    //当发生CustomException时 处理异常  获取异常信息 通过R对象携带返回给前端
    @ExceptionHandler(CustomException.class)
    public R<String> deleteException(CustomException exception){
        String message = exception.getMessage();
        return R.error(message);
    }

}
